package com.firexxx.study.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
 * @description: TODO
 * @author: zhuangzhang2
 * @date: 2021-02-08 22:27
 */
public class Hello{
    private String name;
    private static HttpURLConnection connection = null;

    public static String httpRequest(String url){
        String content = "";
        try{
            URL u = new URL(url);
            connection = (HttpURLConnection)u.openConnection();
            connection.setRequestMethod("GET");
            int code = connection.getResponseCode();
            if(code == 200){
                InputStream in = connection.getInputStream();
                InputStreamReader isr = new InputStreamReader(in,"utf-8");
                BufferedReader reader = new BufferedReader(isr);
                String line = null;
                while((line = reader.readLine()) != null){
                    content += line;
                }
            }
        }catch(MalformedURLException e){
            e.printStackTrace();
        }catch(IOException e){
            e.printStackTrace();
        }finally{
            if(connection != null){
                connection.disconnect();
            }
        }
        return content;
    }

    public static void main(String[] args) throws IOException {
//        String content = httpRequest("http://www.baidu.com/");
//        System.out.println(content);

        URL url = new URL("http://www.baidu.com/");
        Object obj = url.getContent();
        HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
//        InputStream inputStream = httpURLConnection.getInputStream();
        InputStream inputStream = (InputStream) obj;
         BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
        String content = "";
        String line = null;
        while ((line = br.readLine()) != null) {
            content += line;
        }
        System.out.println(content);
    }
}

